﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BTKERP.DAL.DataAccess
{
    internal class ConnectionQueue
    {
        private object _Lock;

        private Connection _Tail;
        private Connection _Header;
        private int _Number;
        private int _Count;

        public ConnectionQueue(int num)
        {
            if (num <= 1)
            {
                num = 1; // At least should have one ;
            }
            _Lock = new object();
            _Number = num;
            for (int i = 0; i < num; i++)
            {
                Connection con = new Connection();
                EnQueue(con);
            }
        }

        ~ConnectionQueue()
        {
            for (int i = 0; i <= _Number; i++)
            {
                Connection con = Dequeue();
                if (con != null)
                    con.Close();
            }
        }

        public Connection Dequeue()
        {
            lock (_Lock)
            {
                if (_Count > 0 && _Header != null)
                {
                    _Count--;
                    Connection result = _Header;
                    _Header = _Header.Next;
                    return result;
                }
            }
            return null;
        }

        public void EnQueue(Connection args)
        {
            if (args == null)
                return;

            lock (_Lock)
            {
                if (_Header == null)
                {
                    _Header = args;
                    _Tail = args;
                }
                else
                {
                    if (_Tail != null)
                    {
                        _Tail.Next = args;
                        _Tail = args;
                    }
                }
                _Count++;
            }
        }
    }
}
